/**
 * 
 */
package cc.dogtailflower.framework.handler;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * set get映射成Java Bean
 * @author cc
 *
 */
public class ModalReflectorHandler {
	
	public static <T> T bindModel(Map<String,Object>map, Class<T> cls) {  
		
		 try {
			T instance = cls.newInstance();
			for(String key : map.keySet()){
				 ModalReflectorHandler.setProperty(instance,key,map.get(key));
			}
            return instance;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Object setProperty(Object bean,String propertyName,Object value){
	
		Class<?> clazz = bean.getClass();
		try{
			Field field = clazz.getDeclaredField(propertyName);
			Method method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[]{field.getType()});
			return method.invoke(bean, new Object[] { value }); 
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
    public static String getGetterName(String propertyName) {  
        String method = "get" + propertyName.substring(0, 1).toUpperCase()  
                + propertyName.substring(1);  
        return method;  
    }  
  
    public static String getSetterName(String propertyName) {  
        String method = "set" + propertyName.substring(0, 1).toUpperCase()  
                + propertyName.substring(1);  
        return method;  
    }  
}
